package com.book.servlet.action;

import com.book.entity.Book;
import com.book.entity.User;
import com.book.service.BookService;
import com.book.service.impl.BookServiceImpl;
import com.book.utils.ThymeleafUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.util.List;

@WebServlet("/modify-book-number")
public class ModifyBookNumber extends HttpServlet {
    BookService bookService;


    @Override
    public void init() throws ServletException {
        bookService = new BookServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Context context = new Context();
        List<Book> books = bookService.listBooks();
        User user = (User) req.getSession().getAttribute("user");
        if(req.getSession().getAttribute("warning")!=null){
            context.setVariable("warning", 1);
            req.getSession().removeAttribute("warning");
        }
        context.setVariable("books", books);
        context.setVariable("nickName", user.getNickname());
        ThymeleafUtil.process("modify_book_number.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if(!req.getParameter("bookId").isEmpty() && !req.getParameter("bookNumber").isEmpty()){
            String bookId = req.getParameter("bookId");
            String bookNumber = req.getParameter("bookNumber");
            bookService.modifyBookNumber(Integer.valueOf(bookId), Integer.valueOf(bookNumber));
            resp.sendRedirect("books");
        }else {
            req.getSession().setAttribute("warning", 1);
            resp.sendRedirect("modify-book-number");
        }
    }
}
